package cc.rengu.igas.bomp.core.model;

import cc.rengu.igas.bomp.common.constant.BompAppParamConstant;
import cc.rengu.igas.bomp.common.constant.DubboMethodConstant;
import cc.rengu.igas.bomp.common.constant.TableNameConstant;
import cc.rengu.igas.bomp.common.dao.*;
import cc.rengu.igas.bomp.common.dao.impl.*;
import cc.rengu.igas.bomp.common.entity.*;
import cc.rengu.igas.bomp.common.enums.*;
import cc.rengu.igas.bomp.common.util.ChangeNextStatusUtil;
import cc.rengu.igas.bomp.common.util.InitParamUtil;
import cc.rengu.igas.bomp.core.realize.MchntImageUnifiedService;
import cc.rengu.igas.bomp.core.realize.impl.MchntImageUnifiedServiceImpl;
import cc.rengu.igas.bomp.facade.enums.BompMchntNatureEnum;
import cc.rengu.igas.bomp.facade.enums.BompSignLicenceTypeEnum;
import cc.rengu.igas.channel.wechat.facade.base.Header;
import cc.rengu.igas.channel.wechat.facade.bean.*;
import cc.rengu.igas.channel.wechat.facade.request.*;
import cc.rengu.igas.channel.wechat.facade.response.*;
import cc.rengu.igas.channel.wechat.facade.result.Result;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.dao.DstChannelCfgMapper;
import cc.rengu.oltp.service.common.dao.SysParamMapper;
import cc.rengu.oltp.service.common.dao.impl.DstChannelCfgMapperImpl;
import cc.rengu.oltp.service.common.dao.impl.SysParamMapperImpl;
import cc.rengu.oltp.service.common.entity.ChannelCallCfg;
import cc.rengu.oltp.service.common.entity.DstChannelCfg;
import cc.rengu.oltp.service.common.entity.SysParam;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.TxnInfo;
import cc.rengu.oltp.service.realize.DubboService;
import cc.rengu.oltp.service.realize.impl.DubboServiceImpl;
import cc.rengu.oltp.utility.util.*;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;
import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.common.utils.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

public class WechatIntegration {

    private RgLogger rglog = RgLog.getLogger(this.getClass().getName());

    public boolean createMerchant(WechatMchntInfo wechatMchntInfo,
                                  String sysSeqNum,
                                  MchntBaseInfo mchntBaseInfo,
                                  TxnInfo txnInfo,
                                  MchntAcctInfo mchntAcctInfo,
                                  MchntSignInfo mchntSignInfo) {
        boolean result = true;
        try {
            //判断是否单独进件
            if (AppParamConstant.NO.equals(wechatMchntInfo.getIndependentEntryFlag()) && !StringUtil.isEmptyOrNull(mchntBaseInfo.getPlatMchntNo())) {
                //平台商户不独立进件，直接返回
                rglog.info("该微信商户不独立进件，微信进件流程结束。");
                //更新商户微信信息表与历史数据表
                wechatMchntInfo.setWechatEntryFlag("01");
                wechatMchntInfo.setLastEntryTime(DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS));
                BizHistory bizHistory = new BizHistory();
                BeanUtil.beanCopy(wechatMchntInfo, bizHistory);
                bizHistory.setManageInstId(mchntBaseInfo.getSignInstId());
                bizHistory.setMchntName(mchntBaseInfo.getMchntName());
                bizHistory.setRealId(wechatMchntInfo.getId());
                bizHistory.setOprTableEname(TableNameConstant.T_B_WECHAT_MCHNT_INFO);
                //修改
                bizHistory.setBizOpr("U");
                String modifyWechatMchntInfoJson = JSONObject.toJSONString(wechatMchntInfo);

                //将正式表的商户信息存入历史表 bizData
                InitParamUtil.initBizHistoryData(bizHistory, modifyWechatMchntInfoJson);
                modifyWechatMchntInfoData(wechatMchntInfo, bizHistory);
                return result;
            }

            //微信进件
            if (null != wechatMchntInfo && StringUtil.isEmptyOrNull(wechatMchntInfo.getWechatMchntNo())) {
                //判断当前状态是否允许修改
                if (!ChangeNextStatusUtil.isAllowModifyData(wechatMchntInfo.getAuditStatus())) {
                    rglog.error("第三方机构商户进件处理失败, 当前微信商户信息待审核，不允许进行进件操作，instId:{},mchntNo:{},当前商户审核状态:{}",
                            wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), wechatMchntInfo.getAuditStatus());
                    throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
                }

                //获取通道服务调用配置-银联微信
                List<ChannelCallCfg> wxNumMapList = txnInfo.getChannelCallCfgList().stream().filter(item -> item.getCallChannelTxn().equals("wcreatemchnt")).sorted(Comparator.comparing(ChannelCallCfg::getCallIndex)).collect(Collectors.toList());
                ChannelCallCfg wxChannelCallCfg = wxNumMapList.get(0);
                WechatCreateMerchantRequest wechatCreateMerchantRequest = initWechatCreateMerchantRequest(sysSeqNum, wechatMchntInfo, wxChannelCallCfg, mchntBaseInfo, mchntSignInfo, mchntAcctInfo);
                DubboService dubboService = new DubboServiceImpl();
                Result<WechatCreateMerchantResponse> wechatResult = (Result<WechatCreateMerchantResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "createMerchant", wechatCreateMerchantRequest);
                if (null == wechatResult || !wechatResult.isSuccess() || !DubboMethodConstant.DUBBO_SUCCESS.equals(wechatResult.getResult().getRespCode())) {
                    rglog.error("微信商户进件处理失败, 当前微信商户信息进件失败，instId:{},mchntNo:{},当前商户审核状态:{}",
                            wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), wechatMchntInfo.getAuditStatus());
                    //更新商户微信信息表与历史数据表 更新入驻失败
                    wechatMchntInfo.setWechatEntryFlag("02");
                    BizHistory bizHistory = new BizHistory();
                    BeanUtil.beanCopy(wechatMchntInfo, bizHistory);
                    bizHistory.setManageInstId(mchntBaseInfo.getSignInstId());
                    bizHistory.setMchntName(mchntBaseInfo.getMchntName());
                    bizHistory.setRealId(wechatMchntInfo.getId());
                    bizHistory.setOprTableEname(TableNameConstant.T_B_WECHAT_MCHNT_INFO);
                    //修改
                    bizHistory.setBizOpr("U");
                    String modifyWechatMchntInfoJson = JSONObject.toJSONString(wechatMchntInfo);

                    //将正式表的商户信息存入历史表 bizData
                    InitParamUtil.initBizHistoryData(bizHistory, modifyWechatMchntInfoJson);
                    modifyWechatMchntInfoData(wechatMchntInfo, bizHistory);
                    result = false;
                } else {
                    //更新商户微信信息表与历史数据表
                    wechatMchntInfo.setWechatMchntNo(wechatResult.getResult().getThirdMchntNo());
                    wechatMchntInfo.setWechatEntryFlag("01");
                    wechatMchntInfo.setLastEntryTime(DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS));
                    BizHistory bizHistory = new BizHistory();
                    BeanUtil.beanCopy(wechatMchntInfo, bizHistory);
                    bizHistory.setManageInstId(mchntBaseInfo.getSignInstId());
                    bizHistory.setMchntName(mchntBaseInfo.getMchntName());
                    bizHistory.setRealId(wechatMchntInfo.getId());
                    bizHistory.setOprTableEname(TableNameConstant.T_B_WECHAT_MCHNT_INFO);
                    //修改
                    bizHistory.setBizOpr("U");
                    String modifyWechatMchntInfoJson = JSONObject.toJSONString(wechatMchntInfo);

                    //将正式表的商户信息存入历史表 bizData
                    InitParamUtil.initBizHistoryData(bizHistory, modifyWechatMchntInfoJson);
                    modifyWechatMchntInfoData(wechatMchntInfo, bizHistory);
                }

            } else if (null != wechatMchntInfo) {
                //更新微信商户信息
                //判断当前状态是否允许修改
                if (!ChangeNextStatusUtil.isAllowModifyData(wechatMchntInfo.getAuditStatus())) {
                    rglog.error("第三方机构商户进件处理失败, 当前微信商户信息待审核，不允许进行进件操作，instId:{},mchntNo:{},当前商户审核状态:{}",
                            wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), wechatMchntInfo.getAuditStatus());
                    throw new BizException(RespCodeEnum.MANAGE_OPERATE_ERROR.getRespCode(), RespCodeEnum.MANAGE_OPERATE_ERROR.getRespDesc());
                }

                //获取通道服务调用配置-银联微信
                List<ChannelCallCfg> wxNumMapList = txnInfo.getChannelCallCfgList().stream().filter(item -> item.getCallChannelTxn().equals("wupdatemchnt")).sorted(Comparator.comparing(ChannelCallCfg::getCallIndex)).collect(Collectors.toList());
                ChannelCallCfg wxChannelCallCfg = wxNumMapList.get(0);

                //组装微信进件修改参数
                WechatUpdateMerchantRequest wechatUpdateMerchantRequest = new WechatUpdateMerchantRequest();
                AddressInfo addressInfo = new AddressInfo();
                addressInfo.setProvinceCode(mchntBaseInfo.getMchntBizProvince());//省
                addressInfo.setCityCode(mchntBaseInfo.getMchntBizCity());//市
                addressInfo.setDistrictCode(mchntBaseInfo.getMchntBizRegion());//区
                addressInfo.setAddress(mchntBaseInfo.getMchntBizAddr());//营业地址

                BeanUtil.beanCopy(wechatMchntInfo, wechatUpdateMerchantRequest);
                Header header = new Header();
                header.setInstId(wechatMchntInfo.getInstId());
                header.setChanlId(ChannelEnum.BOMP.getChannelType());
                header.setSrcSysId(AppParamConstant.SYS_ID);
                header.setTxnNum(wxChannelCallCfg.getCallChannelTxn());
                header.setVersion("1.0.0");
                String channelSeqNum = sysSeqNum + wxChannelCallCfg.getCallIndex();
                header.setTraceNo(channelSeqNum);
                header.setTransTime(DateUtil.getCurrentTime());
                header.setTransDate(DateUtil.getCurrentDate());
                wechatUpdateMerchantRequest.setHeader(header);
                wechatUpdateMerchantRequest.setChannelId(wxChannelCallCfg.getCallChannelId());
                //商户产品信息表的微信支付通道编码
                wechatUpdateMerchantRequest.setChannelType(wechatMchntInfo.getDstChannelType());
                wechatUpdateMerchantRequest.setThirdMchntNo(wechatMchntInfo.getWechatMchntNo());
                wechatUpdateMerchantRequest.setMchntAbbr(mchntBaseInfo.getMchntSimpleName());
                wechatUpdateMerchantRequest.setServicePhone(mchntBaseInfo.getMchntContactPhone());
                wechatUpdateMerchantRequest.setMerRemark(wechatMchntInfo.getMchntNo());

                //商户证件信息
                BankCardInfo bankCardInfo = new BankCardInfo();
                if ("01".equals(mchntBaseInfo.getMchntNature())) {
                    wechatUpdateMerchantRequest.setBusinessLicense(mchntSignInfo.getArtifCertNo());
                    wechatUpdateMerchantRequest.setBusinessLicenseType("IDENTITY_CARD");
                } else {
                    wechatUpdateMerchantRequest.setBusinessLicense(mchntSignInfo.getLicenceCode());
                    wechatUpdateMerchantRequest.setBusinessLicenseType("NATIONAL_LEGAL");
                }
                bankCardInfo.setCardNo(mchntAcctInfo.getSettleAcctNo());
                bankCardInfo.setCardName(mchntAcctInfo.getSettleAcctName());
                bankCardInfo.setBankBranchName(mchntAcctInfo.getAcctOpenBankName());
                wechatUpdateMerchantRequest.setBankcardInfo(bankCardInfo);
                wechatUpdateMerchantRequest.setAddressInfo(addressInfo);
                wechatUpdateMerchantRequest.setPayCtrl("01");

                DubboService dubboService = new DubboServiceImpl();
                Result<WechatUpdateMerchantResponse> wechatResult = (Result<WechatUpdateMerchantResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "updateMerchant", wechatUpdateMerchantRequest);
                if (null == wechatResult || !wechatResult.isSuccess() || !DubboMethodConstant.DUBBO_SUCCESS.equals(wechatResult.getResult().getRespCode())) {
                    //TODO 告警？
                    rglog.error("微信商户信息修改, 当前微信商户信息修改失败，instId:{},mchntNo:{},当前商户审核状态:{}",
                            wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), wechatMchntInfo.getAuditStatus());
                    result = false;
                }
            }
        } catch (Exception e) {
            result = false;
            rglog.error("微信商户信息新增或修改失败，instId:{},mchntNo:{}, 异常原因:{}",
                    wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), e.getMessage());
        }

        return result;
    }

    /**
     * 设置微信支付目录
     *
     * @param wechatMchntInfo 微信商户信息
     * @param sysSeqNum       流水号
     * @param txnInfo         类新
     * @return 结果
     */
    public boolean addJsapiPath(WechatMchntInfo wechatMchntInfo,
                                String sysSeqNum,
                                TxnInfo txnInfo) {
        boolean result = true;
        try {
            if (AppParamConstant.NO.equals(wechatMchntInfo.getIndependentEntryFlag())) {
                //平台商户不独立进件，直接返回
                rglog.info("该微信商户不独立进件，不设置微信支付目录。");
                return result;
            }

            //设置支付目录
            AddJsapiPathRequest addJsapiPathRequest = new AddJsapiPathRequest();
            List<ChannelCallCfg> wxNumMapList = txnInfo.getChannelCallCfgList().stream().filter(item -> item.getCallChannelTxn().equals("addpaypath")).collect(Collectors.toList());
            ChannelCallCfg wxChannelCallCfg = wxNumMapList.get(0);
            String index = wxChannelCallCfg.getCallIndex();
            Header header = new Header();
            header.setInstId(wechatMchntInfo.getInstId());
            header.setChanlId(ChannelEnum.BOMP.getChannelType());
            header.setSrcSysId(AppParamConstant.SYS_ID);
            header.setTxnNum(wxChannelCallCfg.getCallChannelTxn());
            header.setVersion("1.0.0");
            String channelSeqNum = sysSeqNum + index;
            header.setTraceNo(channelSeqNum);
            header.setTransTime(DateUtil.getCurrentTime());
            header.setTransDate(DateUtil.getCurrentDate());

            addJsapiPathRequest.setThirdMchntNo(wechatMchntInfo.getWechatMchntNo());
            addJsapiPathRequest.setHeader(header);
            SysParamMapper sysParamMapper = new SysParamMapperImpl();
            SysParam sysParam = sysParamMapper.selectSysParamByPrimaryKey(wechatMchntInfo.getInstId(), BompAppParamConstant.MCHNT_PARAM_TYPE, BompAppParamConstant.WECHAT_PAY_CATALOG);
            if (null == sysParam) {
                rglog.error("获取微信支付目录设置参数失败， instId:{},mchntNo:{}", wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo());
                throw new BizException(RespCodeEnum.GENERATE_MCHNT_QRCODE_ERROR.getRespCode(), RespCodeEnum.GENERATE_MCHNT_QRCODE_ERROR.getRespDesc());
            }
            addJsapiPathRequest.setJsapiPath(sysParam.getParamValue());
            addJsapiPathRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            addJsapiPathRequest.setChannelType(wechatMchntInfo.getDstChannelType());
            DubboService dubboService = new DubboServiceImpl();
            Result<AddJsapiPathResponse> wechatResult = (Result<AddJsapiPathResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "addJsapiPath", addJsapiPathRequest);
            if (null == wechatResult || !wechatResult.isSuccess() || !DubboMethodConstant.DUBBO_SUCCESS.equals(wechatResult.getResult().getRespCode())) {
                rglog.error("调用微信进行商户支付目录设置, instId:{},mchntNo:{}",
                        wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo());
                result = false;
            }
        } catch (Exception e) {
            result = false;
            rglog.error("调用微信进行商户支付目录设置，instId:{},mchntNo:{}, 异常原因:{}",
                    wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), e.getMessage());
        }

        return result;
    }


    /**
     * 设置微信APPID
     *
     * @param wechatMchntInfo 微信商户信息
     * @param sysSeqNum       流水号
     * @param txnInfo         类新
     * @return 结果
     */
    public boolean bindAppid(WechatMchntInfo wechatMchntInfo,
                             String sysSeqNum,
                             TxnInfo txnInfo) {
        boolean result = true;
        try {
            if (AppParamConstant.NO.equals(wechatMchntInfo.getIndependentEntryFlag())) {
                //平台商户不独立进件，直接返回
                rglog.info("该微信商户不独立进件，不设置微信APPID。");
                return result;
            }

            BindAppidRequest bindAppidRequest = new BindAppidRequest();
            List<ChannelCallCfg> wxNumMapList = txnInfo.getChannelCallCfgList().stream().filter(item -> item.getCallChannelTxn().equals("bindappid")).collect(Collectors.toList());
            ChannelCallCfg wxChannelCallCfg = wxNumMapList.get(0);
            int index = Integer.parseInt(wxChannelCallCfg.getCallIndex());
            Header header = new Header();
            header.setInstId(wechatMchntInfo.getInstId());
            header.setChanlId(ChannelEnum.BOMP.getChannelType());
            header.setSrcSysId(AppParamConstant.SYS_ID);
            header.setTxnNum(wxChannelCallCfg.getCallChannelTxn());
            header.setVersion("1.0.0");

            header.setTransTime(DateUtil.getCurrentTime());
            header.setTransDate(DateUtil.getCurrentDate());
            bindAppidRequest.setHeader(header);
            bindAppidRequest.setThirdMchntNo(wechatMchntInfo.getWechatMchntNo());
            bindAppidRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
            bindAppidRequest.setChannelType(wechatMchntInfo.getDstChannelType());

            Set<String> appSet = new HashSet<>();
            DstChannelCfgMapper dstChannelCfgMapper = new DstChannelCfgMapperImpl();
            DstChannelCfg dstChannelCfg = dstChannelCfgMapper.selectDstChannelCfgByPrimaryKey(wechatMchntInfo.getInstId(), ChannelEnum.WXZF.getChannelType(), wechatMchntInfo.getDstChannelType());
            appSet.add(dstChannelCfg.getSubAppId());

            if (!StringUtil.isEmptyOrNull(wechatMchntInfo.getAppId())) {
                appSet.add(wechatMchntInfo.getAppId());
            }

            if (!StringUtil.isEmptyOrNull(wechatMchntInfo.getMiniAppId())) {
                appSet.add(wechatMchntInfo.getMiniAppId());
            }

            DubboService dubboService = new DubboServiceImpl();
            for (String appId : appSet) {
                String channelSeqNum = sysSeqNum + index;
                header.setTraceNo(channelSeqNum);
                bindAppidRequest.setSubAppId(appId);
                bindAppidRequest.setHeader(header);
                Result<BindAppidResponse> wechatResult = (Result<BindAppidResponse>) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "bindAppid", bindAppidRequest);
                if (null == wechatResult || !wechatResult.isSuccess() || !DubboMethodConstant.DUBBO_SUCCESS.equals(wechatResult.getResult().getRespCode())) {
                    rglog.error("调用微信进行商户绑定微信APPID失败, instId:{},mchntNo:{},appId:{}",
                            wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), appId);
                    result = false;
                }
                index++;
            }

        } catch (Exception e) {
            result = false;
            rglog.error("调用微信进行商户绑定微信APPID异常，instId:{},mchntNo:{}, 异常原因:{}",
                    wechatMchntInfo.getInstId(), wechatMchntInfo.getMchntNo(), e.getMessage());
        }

        return result;
    }


    private WechatCreateMerchantRequest initWechatCreateMerchantRequest(String sysSeqNum,
                                                                        WechatMchntInfo wechatMchntInfo,
                                                                        ChannelCallCfg channelCallCfg,
                                                                        MchntBaseInfo mchntBaseInfo,
                                                                        MchntSignInfo mchntSignInfo,
                                                                        MchntAcctInfo mchntAcctInfo) throws Exception {

        WechatCreateMerchantRequest wechatCreateMerchantRequest = new WechatCreateMerchantRequest();
        BeanUtil.beanCopy(wechatMchntInfo, wechatCreateMerchantRequest);
        Header header = new Header();
        header.setInstId(wechatMchntInfo.getInstId());
        header.setChanlId(ChannelEnum.BOMP.getChannelType());
        header.setSrcSysId(AppParamConstant.SYS_ID);
        header.setTxnNum(channelCallCfg.getCallChannelTxn());
        header.setVersion("1.0.0");
        String channelSeqNum = sysSeqNum + channelCallCfg.getCallIndex();
        header.setTraceNo(channelSeqNum);
        header.setTransTime(DateUtil.getCurrentTime());
        header.setTransDate(DateUtil.getCurrentDate());
        wechatCreateMerchantRequest.setHeader(header);
        wechatCreateMerchantRequest.setChannelId(channelCallCfg.getCallChannelId());
        //商户产品信息表的微信支付通道编码
        wechatCreateMerchantRequest.setChannelType(wechatMchntInfo.getDstChannelType());
        wechatCreateMerchantRequest.setMchntNo(mchntBaseInfo.getMchntNo());
        wechatCreateMerchantRequest.setServicePhone(mchntBaseInfo.getMchntContactPhone());
        wechatCreateMerchantRequest.setContact(mchntBaseInfo.getMchntContactName());
        AddressInfo addressInfo = new AddressInfo();
        addressInfo.setProvinceCode(mchntBaseInfo.getMchntBizProvince());//省
        addressInfo.setCityCode(mchntBaseInfo.getMchntBizCity());//市
        addressInfo.setDistrictCode(mchntBaseInfo.getMchntBizRegion());//区
        addressInfo.setAddress(mchntBaseInfo.getMchntBizAddr());//营业地址


        //默认对公
        String publicPrivateKey = "01";
        BompMchntNatureEnum wechatType = BompMchntNatureEnum.getBompMchntNatureEnumByType(mchntBaseInfo.getMchntNature());
        if (null != wechatType) {
            //根据商户性质判断对公对私
            publicPrivateKey = wechatType.getWechatPublicPrivateKey();
        }
        IndustryMapInfoMapper industryMapInfoMapper = new IndustryMapInfoMapperImpl();
        IndustryMapInfo wechatIndustry = industryMapInfoMapper.selectIndustryMapInfoByIndustryTypeAndChannelType(mchntBaseInfo.getIndustryType(), ChannelEnum.WXZF.getChannelType(), publicPrivateKey);
        if (null == wechatIndustry) {
            //默认使用对公再次查询，若还查无数据则失败
            wechatIndustry = industryMapInfoMapper.selectIndustryMapInfoByIndustryTypeAndChannelType(mchntBaseInfo.getIndustryType(), ChannelEnum.WXZF.getChannelType(), "01");
            if (null == wechatIndustry) {
                rglog.error("通过行业类型查询微信行业类型映射关系失败！，instId:{},mchntNo:{},industryType:{}",
                        mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo(), mchntBaseInfo.getIndustryType());
                throw new BizException(RespCodeEnum.ILLEGAL_OPERATION.getRespCode(), RespCodeEnum.ILLEGAL_OPERATION.getRespDesc());
            }
        }

        //商户经营类目
        wechatCreateMerchantRequest.setBusiness(wechatIndustry.getDestCatalogCd());
        wechatCreateMerchantRequest.setMchntName(mchntBaseInfo.getMchntName());
        wechatCreateMerchantRequest.setMchntAbbr(mchntBaseInfo.getMchntSimpleName());
        if (!StringUtil.isEmptyOrNull((mchntBaseInfo.getMchntContactPhone()))) {
            wechatCreateMerchantRequest.setServicePhone(mchntBaseInfo.getMchntContactPhone());
        } else {
            if (StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntContactMobile())) {
                rglog.error("商户基本信息-联系人固话/联系人手机号均为空.");
                throw new BizException("联系人固话/联系人手机号均为空");
            } else {
                wechatCreateMerchantRequest.setServicePhone(mchntBaseInfo.getMchntContactMobile());
            }
        }
        wechatCreateMerchantRequest.setContact(mchntBaseInfo.getMchntContactName());
        wechatCreateMerchantRequest.setContactPhone(mchntBaseInfo.getMchntContactMobile());
        wechatCreateMerchantRequest.setContactEmail(mchntBaseInfo.getMchntContactEmail());

        //商户证件信息
        BankCardInfo bankCardInfo = new BankCardInfo();
        if ("01".equals(mchntBaseInfo.getMchntNature())) {
            wechatCreateMerchantRequest.setBusinessLicense(mchntSignInfo.getArtifCertNo());
            wechatCreateMerchantRequest.setBusinessLicenseType("IDENTITY_CARD");
        } else {
            wechatCreateMerchantRequest.setBusinessLicense(mchntSignInfo.getLicenceCode());
            wechatCreateMerchantRequest.setBusinessLicenseType("NATIONAL_LEGAL");
        }
        bankCardInfo.setCardNo(mchntAcctInfo.getSettleAcctNo());
        bankCardInfo.setCardName(mchntAcctInfo.getSettleAcctName());
        bankCardInfo.setBankBranchName(mchntAcctInfo.getAcctOpenBankName());
        wechatCreateMerchantRequest.setBankcardInfo(bankCardInfo);
        wechatCreateMerchantRequest.setAddressInfo(addressInfo);

        return wechatCreateMerchantRequest;
    }

    private void modifyWechatMchntInfoData(WechatMchntInfo wechatMchntInfo, BizHistory bizHistory) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.MCMP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.MCMP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();

        WechatMchntInfoMapper wechatMchntInfoMapper = new WechatMchntInfoMapperImpl();
        int dbResult = wechatMchntInfoMapper.updateWechatMchntInfoById(wechatMchntInfo);
        if (dbResult != 0) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("微信商户进件-修改微信商户信息表失败！id:{},mchnt:{},instId:{}",
                    wechatMchntInfo.getId(), wechatMchntInfo.getMchntNo(), wechatMchntInfo.getInstId());
            throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
        }


        if (null != bizHistory) {
            bizHistory.setCreateTime(DateUtil.getCurrentDateTime(InitParamUtil.yyyy_MM_dd_HHmmssSSS));
            BizHistoryMapper bizHistoryMapper = new BizHistoryMapperImpl();
            dbResult = bizHistoryMapper.insertBompBizHistory(bizHistory);
            if (dbResult != 0) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("微信商户进件-新增业务历史表记录失败！realId:{},manageInstId:{},instId:{}",
                        bizHistory.getRealId(), bizHistory.getManageInstId(), bizHistory.getInstId());
                throw new BizException(RespCodeEnum.DATABASE_OPR_ERROR.getRespCode(), RespCodeEnum.DATABASE_OPR_ERROR.getRespDesc());
            }
        }

        dbsUtil.dbsEndTransaction(true);
    }

    /**
     * 微信实名认证
     *
     * @param mchntBaseInfo 商户基本信息
     * @throws Exception 异常
     */
    public void beforeRealNameCheck(MchntBaseInfo mchntBaseInfo) throws Exception {
        SysParam realNameFlagSysParam = SysParamEnum.getSysParam(mchntBaseInfo.getInstId(), SysParamEnum.REAL_NAME_FLAG);
        if (null == realNameFlagSysParam) {
            rglog.error("当前行未开通实名认证业务.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "当前行未开通实名认证业务");
        }
        if (MchntTypeEnum.CHAIN_MCHNT_STORE.getMchntType().equals(mchntBaseInfo.getMchntType()) && AppParamConstant.NO.equals(mchntBaseInfo.getIndependentDataFlag())) {
            rglog.info("连锁商户门店非独立维护资料,不进行实名认证.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "连锁商户门店非独立维护资料,不进行实名认证");
        }

        MchntAuthCtrlMapper mchntAuthCtrlMapper = new MchntAuthCtrlMapperImpl();
        List<MchntAuthCtrl> mchntAuthCtrlList = mchntAuthCtrlMapper.selectMchntAuthCtrlInfoByMchntNo(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        boolean isHaveWechatAuth = false;
        if (!CollectionUtils.isEmpty(mchntAuthCtrlList)) {
            for (MchntAuthCtrl mchntAuthCtrl : mchntAuthCtrlList) {
                if (AppParamConstant.YES.equals(mchntAuthCtrl.getSupportFlag()) && WechatMchntAuthEnum.isWechatAuth(mchntAuthCtrl)) {
                    isHaveWechatAuth = true;
                    break;
                }
            }
        }
        if (!isHaveWechatAuth) {
            rglog.info("商户<{}>无微信支付产品,不校验实名认证材料.", mchntBaseInfo.getMchntNo());
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "无微信支付产品,无需微信实名认证");
        }
    }

    private MchntBaseInfo mchntBaseInfo;
    private MchntSignInfo mchntSignInfo;
    private WechatMchntInfo wechatMchntInfo;
    private List<MchntImageInfo> mchntImageInfoList;
    private List<MchntApexInfo> mchntApexInfoList;
    /**
     * 主体类型
     */
    private String subjectType;

    /**
     * 微信实名认证申请
     *
     * @param mchntBaseInfo 商户基本信息
     * @return 微信商户信息
     * @throws Exception 异常
     */
    public WechatMchntInfo realNameApplyment(MchntBaseInfo mchntBaseInfo) throws Exception {
        this.mchntBaseInfo = mchntBaseInfo;

        //签约信息
        MchntSignInfoMapper mchntSignInfoMapper = new MchntSignInfoMapperImpl();
        mchntSignInfo = mchntSignInfoMapper.selectMchntSignInfoByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        if (null == mchntSignInfo) {
            rglog.error("无商户签约信息.");
            throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
        }

        //商户影像信息
        MchntImageInfoMapper mchntImageInfoMapper = new MchntImageInfoMapperImpl();
        mchntImageInfoList = mchntImageInfoMapper.selectMchntImageInfoByMchntNo(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());
        if (!CollectionUtils.isEmpty(mchntImageInfoList)) {
            mchntImageInfoList = mchntImageInfoList.stream().filter(item -> AppParamConstant.YES.equals(item.getRecordStatus())).collect(Collectors.toList());
        }

        //微信商户信息
        WechatMchntInfoMapper wechatMchntInfoMapper = new WechatMchntInfoMapperImpl();
        wechatMchntInfo = wechatMchntInfoMapper.selectWechatMchntInfoByPrimaryKey(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());

        //拓展属性
        MchntApexInfoMapper mchntApexInfoMapper = new MchntApexInfoMapperImpl();
        mchntApexInfoList = mchntApexInfoMapper.selectMchntApexInfoByMchntNo(mchntBaseInfo.getInstId(), mchntBaseInfo.getMchntNo());

        //主体类型
        subjectType = WechatSubjectTypeEnum.getWechatSubjectTypeByMchntNature(mchntBaseInfo.getMchntNature());

        checkWechatRealNameApplymentParam();

        wechatRealNameApplyment();
        return wechatMchntInfo;
    }

    private void checkWechatRealNameApplymentParam() throws Exception {
        if (mchntBaseInfo.getAuditStatus().endsWith("1") || mchntBaseInfo.getAuditStatus().endsWith("4")) {
            rglog.error("商户待审核,需审核通过后操作.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "商户待审核,需审核通过/拒绝后操作");
        }

        if (null == wechatMchntInfo) {
            rglog.error("无微信商户信息.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "无微信商户信息");
        }
        if (!"01".equals(wechatMchntInfo.getWechatEntryFlag())) {
            rglog.error("未微信商户进件.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "未微信商户进件");
        }
        if (StringUtil.isEmptyOrNull(wechatMchntInfo.getWechatMchntNo())) {
            rglog.error("未微信商户进件.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "未微信商户进件");
        }
        if (AppParamConstant.NO.equals(wechatMchntInfo.getIndependentEntryFlag())) {
            rglog.error("非独立进件,无需实名认证.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "非独立进件,无需实名认证");
        }
        if (AppParamConstant.YES.equals(wechatMchntInfo.getRealNameFlag())) {
            rglog.error("已微信实名认证.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "已微信实名认证");
        }
        if (WechatRealNameApplyStatusEnum.WECHAT_REAL_NAME_APPLYING.equals(wechatMchntInfo.getRealNameFlag())) {
            rglog.error("微信实名认证申请中.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "微信实名认证申请中");
        }
        if (WechatRealNameApplyStatusEnum.WECHAT_REAL_NAME_MCHNT_CONFIRMED.equals(wechatMchntInfo.getRealNameFlag())) {
            rglog.error("微信实名待商户确认.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "微信实名待商户确认");
        }

        if (CollectionUtils.isEmpty(mchntImageInfoList)) {
            rglog.error("请补全商户影像信息.");
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "请补全商户影像信息");
        }
    }

    private void wechatRealNameApplyment() throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        String sysSeqNum = xmlTreeUtil.getXmlTreeStringValue(TreeNodeConstant.SYS_SEQ_NUM);

        List<ImageTypeEnum> imageTypeEnumList = new ArrayList<>();
        checkMchntParam(imageTypeEnumList);
        checkImageInfo(imageTypeEnumList);

        WechatRealNameApplymentRequest wechatRealNameApplymentRequest = initWechatRealNameApplymentRequest(sysSeqNum);

        DubboService dubboService = new DubboServiceImpl();
        Result result = (Result) dubboService.callDubboService(DubboMethodConstant.DUBBO_WECHAT_MCHNT_SERVICE, "realNameApplyment", wechatRealNameApplymentRequest);
        if (null == result || !result.isSuccess() || null == result.getResult()) {
            rglog.error("调用实名认证失败.");
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        }
        WechatRealNameApplymentResponse wechatRealNameApplymentResponse = (WechatRealNameApplymentResponse) result.getResult();
        if (DubboMethodConstant.DUBBO_SUCCESS.equals(wechatRealNameApplymentResponse.getRespCode())) {
            wechatMchntInfo.setRealNameApplyNo(wechatRealNameApplymentResponse.getApplymentId());
            wechatMchntInfo.setRealNameFlag(WechatRealNameApplyStatusEnum.WECHAT_REAL_NAME_APPLYING);
        } else if (DubboMethodConstant.DUBBO_OVERTIME.equals(wechatRealNameApplymentResponse.getRespCode())
                || OltpRpcdEnum.BIZ_PROCESS_TIMEOUT.getRespCode().equals(wechatRealNameApplymentResponse.getRespCode())) {
            rglog.error("调用实名认证超时.");
            throw new BizException(RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespCode(), RespCodeEnum.CALL_BIZ_SERVICE_ERROR.getRespDesc());
        } else {
            rglog.error("调用实名认证失败.");
            throw new BizException(wechatRealNameApplymentResponse.getRespCode(), wechatRealNameApplymentResponse.getRespDesc());
        }

        wechatMchntInfo.setRealNameApplyNo(wechatRealNameApplymentResponse.getApplymentId());
        //更新实名认证业务单号 为请求traceNo
        wechatMchntInfo.setRealNameBizNo(sysSeqNum);
        wechatMchntInfo.setLastOprId(mchntBaseInfo.getLastOprId());
        wechatMchntInfo.setLastUpdateTime(DateUtil.getCurrentDateTime(BompAppParamConstant.yyyy_MM_dd_HHmmssSSS));
        wechatMchntInfo.setLastRealTime(wechatMchntInfo.getLastUpdateTime());

        BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
        BizTmp wechatMchntInfoBizTmp = bizTmpMapper.selectBizTmpByRealId(wechatMchntInfo.getInstId(), wechatMchntInfo.getId());
        WechatMchntInfo bizTmpWechatMchntInfo = JSONObject.parseObject(InitParamUtil.getJsonString(wechatMchntInfoBizTmp), WechatMchntInfo.class);
        bizTmpWechatMchntInfo.setRealNameApplyNo(wechatMchntInfo.getRealNameApplyNo());
        bizTmpWechatMchntInfo.setRealNameFlag(wechatMchntInfo.getRealNameFlag());
        bizTmpWechatMchntInfo.setRealNameBizNo(wechatMchntInfo.getRealNameBizNo());
        bizTmpWechatMchntInfo.setLastOprId(wechatMchntInfo.getLastOprId());
        bizTmpWechatMchntInfo.setLastUpdateTime(wechatMchntInfo.getLastUpdateTime());
        bizTmpWechatMchntInfo.setLastRealTime(wechatMchntInfo.getLastRealTime());
        InitParamUtil.initBizTempData(wechatMchntInfoBizTmp, JSONObject.toJSONString(bizTmpWechatMchntInfo));
        updateWechatMchntInfoAndBizTmp(wechatMchntInfo, wechatMchntInfoBizTmp);
    }

    private void checkMchntParam(List<ImageTypeEnum> imageTypeEnumList) throws Exception {
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_INSTITUTIONS_CLONED.getType().equals(subjectType)) {
            imageTypeEnumList.add(ImageTypeEnum.COMPANY_PROVE);
        }

        //联系人信息
        if (StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntContactName())
                || StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntContactPhone())
                || StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntContactCertNo())) {
            rglog.error("请补齐商户联系人<{}>、联系人电话<{}>、联系人证件号等信息<{}>.", mchntBaseInfo.getMchntContactName(), mchntBaseInfo.getMchntContactPhone(), mchntBaseInfo.getMchntContactCertNo());
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "请补齐商户联系人、联系人电话、联系人证件号等信息");
        }

        //主体信息-营业执照信息
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_ENTERPRISE.getType().equals(subjectType)
                || WechatSubjectTypeEnum.SUBJECT_TYPE_INDIVIDUAL.getType().equals(subjectType)) {
            if (!LicenseTypeEnum.BUSINESS_LICENSE.getLicenseType().equals(mchntSignInfo.getLicenceType())) {
                rglog.error("企业或个体,营业执照类型<{}>必须是[{}]", mchntSignInfo.getLicenceType(), LicenseTypeEnum.BUSINESS_LICENSE.getLicenseType());
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "企业或个体,营业执照类型必须是营业执照");
            }
            if (StringUtil.isEmptyOrNull(mchntSignInfo.getLicenceEffectiveDate()) || StringUtil.isEmptyOrNull(mchntSignInfo.getLicenceExpiryDate())) {
                rglog.error("营业执照有效期<{}>-<{}>为空.", mchntSignInfo.getLicenceEffectiveDate(), mchntSignInfo.getLicenceExpiryDate());
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "请补全营业执照有效期");
            }
            imageTypeEnumList.add(ImageTypeEnum.BUSINESS_LICENSE);

            if (StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizAddr())) {
                rglog.error("需补全商户营业地址.");
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "需补全商户营业地址");
            }
        }

        //主体信息-登记证书信息
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_INSTITUTIONS_CLONED.getType().equals(subjectType)) {
            if (!BompSignLicenceTypeEnum.isWechatRealNameLicenceType(mchntSignInfo.getLicenceType())) {
                rglog.error("事业单位,营业执照类型<{}>不是微信所需证件类型.", mchntSignInfo.getLicenceType());
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "事业单位,营业执照类型必须是营业执照");
            }
            if (StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizAddr())) {
                rglog.error("需补全商户营业地址.");
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "需补全商户营业地址");
            }
        }

        //主体信息-辅助证明材料信息
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_MICRO.getType().equals(subjectType)) {
            List<MchntApexInfo> microBizTypeSysParamList = mchntApexInfoList.stream().filter(item -> MchntApexPropeytyEnum.MICRO_BIZ_TYPE.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(microBizTypeSysParamList)) {
                rglog.error("商户性质为小微商户,需补全[小微经营类型]属性");
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "商户性质为小微商户,需补全[小微经营类型]属性");
            }
            MchntApexInfo microBizTypeSysParam = microBizTypeSysParamList.get(0);
            if (!BompAppParamConstant.MICRO_TYPE_STORE.equals(microBizTypeSysParam.getPropertyValue())
                    && !BompAppParamConstant.MICRO_TYPE_MOBILE.equals(microBizTypeSysParam.getPropertyValue())
                    && !BompAppParamConstant.MICRO_TYPE_ONLINE.equals(microBizTypeSysParam.getPropertyValue())) {
                rglog.error("小微经营类型<{}>不符合枚举.", microBizTypeSysParam.getPropertyValue());
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "[小微经营类型]属性错误,请重新录入");
            }

            if (StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizProvince())
                    || StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizCity())
                    || StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizRegion())
                    || StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntBizAddr())) {
                rglog.error("商户地址信息为空.");
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "请补全商户营业地址");
            }

            imageTypeEnumList.add(ImageTypeEnum.SHOP_FRONT_PHOTO);
            imageTypeEnumList.add(ImageTypeEnum.SHOP_ENVIRONMENT_PHOTO);
        }

        //法人身份信息
        if (!ArtifCertTypeEbnum.isWechatRealNameArtifCertType(mchntSignInfo.getArtifCertType())) {
            rglog.error("证件类型<{}>非微信所需.", mchntSignInfo.getArtifCertType());
            throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "法人证件类型不属于[身份证][护照][港澳来往内地通行证][台湾同胞来往内地通行证]");
        }
        imageTypeEnumList.add(ImageTypeEnum.ARTIF_FACE_CERT_IMAGE);
        imageTypeEnumList.add(ImageTypeEnum.ARTIF_BACK_CERT_IMAGE);
    }

    private void checkImageInfo(List<ImageTypeEnum> imageTypeEnumList) throws Exception {
        String imageBasePath = "";
        SysParam imagePathSysParam = SysParamEnum.getSysParam(mchntBaseInfo.getInstId(), SysParamEnum.localStorageRootPath);
        if (null != imagePathSysParam && AppParamConstant.YES.equals(imagePathSysParam.getParamStatus())) {
            // imageBasePath = imagePathSysParam.getParamValue() + File.separator;
            imageBasePath = imagePathSysParam.getParamValue() + "/";
        }
        MchntImageUnifiedService mchntImageUnifiedService = new MchntImageUnifiedServiceImpl(imageBasePath);

        for (ImageTypeEnum imageTypeEnum : imageTypeEnumList) {
            List<MchntImageInfo> mchntImageInfos = mchntImageInfoList.stream().filter(item ->
                    imageTypeEnum.getImageType().equals(item.getImageType()) && AppParamConstant.YES.equals(item.getRecordStatus())).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(mchntImageInfos)) {
                rglog.error("缺少类型<{}>-<{}>图片", imageTypeEnum.getImageType(), imageTypeEnum.getImageDesc());
                throw new BizException(RespCodeEnum.WECHAT_REAL_NAME_APPLY_ERROR.getRespCode(), "请补充微信实名认证所需材料,缺少影像:" + imageTypeEnum.getImageDesc());
            }
            MchntImageInfo mchntImageInfo = mchntImageInfos.get(0);
            if (StringUtil.isEmptyOrNull(mchntImageInfo.getWechatMediaId())) {
                rglog.info("ID<{}>影像<{}>序号<{}>,尝试上传微信.", mchntImageInfo.getId(), mchntImageInfo.getImageType(), mchntImageInfo.getImageIndex());
                mchntImageUnifiedService.uploadToWechat(mchntBaseInfo, wechatMchntInfo, mchntImageInfo);
            }
        }
    }

    private WechatRealNameApplymentRequest initWechatRealNameApplymentRequest(String sysSeqNum) throws Exception {

        WechatRealNameApplymentRequest wechatRealNameApplymentRequest = new WechatRealNameApplymentRequest();
        Header header = InitParamUtil.initWechatHeader("applyment", mchntBaseInfo.getInstId(), sysSeqNum);
        wechatRealNameApplymentRequest.setHeader(header);
        wechatRealNameApplymentRequest.setChannelId(ChannelEnum.WXZF.getChannelType());
        wechatRealNameApplymentRequest.setChannelType(wechatMchntInfo.getDstChannelType());
        wechatRealNameApplymentRequest.setBusinessCode(sysSeqNum);

        //联系人信息
        ContactInfo contactInfo = new ContactInfo();
        contactInfo.setContactName(mchntBaseInfo.getMchntContactName());
        if (!StringUtil.isEmptyOrNull(mchntBaseInfo.getMchntContactPhone())) {
            contactInfo.setContactPhone(mchntBaseInfo.getMchntContactPhone());
        } else {
            contactInfo.setContactPhone(mchntBaseInfo.getMchntContactMobile());
        }
        contactInfo.setCertId(mchntBaseInfo.getMchntContactCertNo());
        wechatRealNameApplymentRequest.setContactInfo(contactInfo);

        //主体信息
        SubjectInfo subjectInfo = initSubjectInfo();
        wechatRealNameApplymentRequest.setSubjectInfo(subjectInfo);

        //法人信息
        IdentificationInfo identificationInfo = new IdentificationInfo();
        identificationInfo.setCertType(WechatCertTypeEnum.getWechatCertTypeEnumByType(mchntSignInfo.getArtifCertType()));
        identificationInfo.setName(mchntSignInfo.getArtifName());
        identificationInfo.setCertNo(mchntSignInfo.getArtifCertNo());
        //正面照
        List<MchntImageInfo> artifFaceCertImageList = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.ARTIF_FACE_CERT_IMAGE.getImageType().equals(item.getImageType())).collect(Collectors.toList());
        identificationInfo.setFrontImageId(artifFaceCertImageList.get(0).getWechatMediaId());
        //反面照
        List<MchntImageInfo> artifBackCertImageList = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.ARTIF_BACK_CERT_IMAGE.getImageType().equals(item.getImageType())).collect(Collectors.toList());
        identificationInfo.setBackImageId(artifBackCertImageList.get(0).getWechatMediaId());
        // 示例值：[\"1970-01-01\",\"forever\"]
        String validDate = convertToWechatValidDate(mchntSignInfo.getCertEffectiveDate(), mchntSignInfo.getCertExpiryDate());
        identificationInfo.setValidDate(validDate);
        wechatRealNameApplymentRequest.setIdentificationInfo(identificationInfo);
        return wechatRealNameApplymentRequest;
    }


    //region 初始化主体信息

    /**
     * 初始化主体信息
     */
    private SubjectInfo initSubjectInfo() throws Exception {
        SubjectInfo subjectInfo = new SubjectInfo();
        subjectInfo.setSubjectType(subjectType);

        //主体类型为事业单位时，单位证明函照片必填
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_INSTITUTIONS_CLONED.getType().equals(subjectInfo.getSubjectType())) {
            List<MchntImageInfo> companyProveMchntImageInfoList = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.COMPANY_PROVE.getImageType().equals(item.getImageType())).collect(Collectors.toList());
            subjectInfo.setCompanyProveImage(companyProveMchntImageInfoList.get(0).getWechatMediaId());
        }

        LicenceInfo licenceInfo = initLicenceInfo();
        subjectInfo.setLicenceInfo(licenceInfo);

        CertificateInfo certificateInfo = initCertificateInfo();
        subjectInfo.setCertificateInfo(certificateInfo);

        AssistProveInfo assistProveInfo = initAssistProveInfo();
        subjectInfo.setAssistProveInfo(assistProveInfo);

        return subjectInfo;
    }

    private LicenceInfo initLicenceInfo() {
        LicenceInfo licenceInfo = new LicenceInfo();
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_ENTERPRISE.getType().equals(subjectType)
                || WechatSubjectTypeEnum.SUBJECT_TYPE_INDIVIDUAL.getType().equals(subjectType)) {
            //主体类型为企业或个体户时，营业执照信息必填
            MchntImageInfo licenceImage = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.BUSINESS_LICENSE.getImageType().equals(item.getImageType())).collect(Collectors.toList()).get(0);

            licenceInfo.setLicenceNo(mchntSignInfo.getLicenceCode());
            licenceInfo.setLicenceImageId(licenceImage.getWechatMediaId());
            licenceInfo.setMchntName(mchntBaseInfo.getMchntName());
            licenceInfo.setLegalPerson(mchntSignInfo.getArtifName());
            licenceInfo.setAddress(mchntBaseInfo.getMchntBizAddr());
            //示例值：[\"1970-01-01\",\"forever\"]
            String validDate = convertToWechatValidDate(mchntSignInfo.getLicenceEffectiveDate(), mchntSignInfo.getLicenceExpiryDate());
            licenceInfo.setValidDate(validDate);

        }
        return licenceInfo;
    }

    private CertificateInfo initCertificateInfo() {
        CertificateInfo certificateInfo = new CertificateInfo();
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_INSTITUTIONS_CLONED.getType().equals(subjectType)
                || WechatSubjectTypeEnum.SUBJECT_TYPE_OTHERS.getType().equals(subjectType)) {
            //主体类型为事业单位或其他组织时，登记证书信息必填
            List<MchntImageInfo> licenceImageList = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.BUSINESS_LICENSE.getImageType().equals(item.getImageType())).collect(Collectors.toList());

            certificateInfo.setCertType(BompSignLicenceTypeEnum.getWechatCertTypeByLicenceType(mchntSignInfo.getLicenceType()));
            certificateInfo.setCertNum(mchntSignInfo.getLicenceCode());
            certificateInfo.setCertImageId(licenceImageList.get(0).getWechatMediaId());
            certificateInfo.setMchntName(mchntBaseInfo.getMchntName());
            certificateInfo.setLegalPerson(mchntSignInfo.getArtifName());
            certificateInfo.setAddress(mchntBaseInfo.getMchntBizAddr());
            //示例值：[\"1970-01-01\",\"forever\"]
            //证书有效期
            String validDate = convertToWechatValidDate(mchntSignInfo.getLicenceEffectiveDate(), mchntSignInfo.getLicenceExpiryDate());
            certificateInfo.setValidDate(validDate);
        }
        return certificateInfo;
    }

    private AssistProveInfo initAssistProveInfo() {
        AssistProveInfo assistProveInfo = new AssistProveInfo();
        if (WechatSubjectTypeEnum.SUBJECT_TYPE_MICRO.getType().equals(subjectType)) {
            //主体类型为小微商户时必填
            List<MchntApexInfo> microBizTypeSysParamList = mchntApexInfoList.stream().filter(item -> MchntApexPropeytyEnum.MICRO_BIZ_TYPE.getPropertyKey().equals(item.getPropertyKey())).collect(Collectors.toList());
            MchntApexInfo microBizTypeSysParam = microBizTypeSysParamList.get(0);
            assistProveInfo.setMicroBizType(microBizTypeSysParam.getPropertyValue());

            assistProveInfo.setStoreName(mchntBaseInfo.getMchntName());
            assistProveInfo.setAddressCode(mchntBaseInfo.getMchntBizProvince() + mchntBaseInfo.getMchntBizCity() + mchntBaseInfo.getMchntBizRegion());
            assistProveInfo.setStoreAddress(mchntBaseInfo.getMchntBizAddr());
            //门头照
            MchntImageInfo mchntShopFront = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.SHOP_FRONT_PHOTO.getImageType().equals(item.getImageType())).collect(Collectors.toList()).get(0);
            assistProveInfo.setHeaderImageId(mchntShopFront.getWechatMediaId());
            //店内照片
            MchntImageInfo businessSiteImage = mchntImageInfoList.stream().filter(item -> ImageTypeEnum.SHOP_ENVIRONMENT_PHOTO.getImageType().equals(item.getImageType())).collect(Collectors.toList()).get(0);
            assistProveInfo.setIndoorImageId(businessSiteImage.getWechatMediaId());
        }
        return assistProveInfo;
    }

    /**
     * [\"1970-01-01\",\"forever\"]
     *
     * @param startDate 开始日期
     * @param endDate   结束日期
     * @return 格式
     */
    private String convertToWechatValidDate(String startDate, String endDate) {
        return "[\"" + DateUtil.formatDate(DateUtil.getDateStamp(startDate, "yyyyMMdd"), "yyyy-MM-dd")
                + "\",\"" + DateUtil.formatDate(DateUtil.getDateStamp(endDate, "yyyyMMdd"), "yyyy-MM-dd") + "\"]";
    }

    //endregion

    /**
     * 更新微信商户信息表和临时表
     *
     * @param mchntBaseInfo
     * @param wechatMchntInfo
     * @throws Exception
     */
    public void updateWechatMchntInfoAndBizTmp(MchntBaseInfo mchntBaseInfo, WechatMchntInfo wechatMchntInfo) throws Exception {
        DbsUtil dbsUtil = InitParamUtil.dbsBeginTransaction(AppConfigConstant.MCMP_POOL_NAME);
        try {
            WechatMchntInfoMapper wechatMchntInfoMapper = new WechatMchntInfoMapperImpl();
            int dbResult = wechatMchntInfoMapper.updateWechatMchntInfoById(wechatMchntInfo);
            if (0 != dbResult) {
                rglog.error("更新微信商户信息失败.");
                throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
            }

            BizTmp bizTmp = InitParamUtil.initBizTmpInfo(mchntBaseInfo, TableNameConstant.T_B_WECHAT_MCHNT_INFO, BompBizOprEnum.UPDATE.getBizOprCode(), wechatMchntInfo);
            BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
            dbResult = bizTmpMapper.updateBizTmpByRealId(bizTmp);
            if (0 != dbResult) {
                rglog.error("更新微信商户信息<{}>临时表失败.", wechatMchntInfo.getId());
                throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
            }
            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error(cc.rengu.utility.base.StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
        }
    }

    public void updateWechatMchntInfoAndBizTmp(WechatMchntInfo wechatMchntInfo, BizTmp wechatMchntInfoBizTmp) throws Exception {
        DbsUtil dbsUtil = InitParamUtil.dbsBeginTransaction(AppConfigConstant.MCMP_POOL_NAME);
        try {
            WechatMchntInfoMapper wechatMchntInfoMapper = new WechatMchntInfoMapperImpl();
            int dbResult = wechatMchntInfoMapper.updateWechatMchntInfoById(wechatMchntInfo);
            if (0 != dbResult) {
                rglog.error("更新微信商户信息失败.");
                throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
            }

            BizTmpMapper bizTmpMapper = new BizTmpMapperImpl();
            dbResult = bizTmpMapper.updateBizTmpByRealId(wechatMchntInfoBizTmp);
            if (0 != dbResult) {
                rglog.error("更新微信商户信息<{}>临时表失败.", wechatMchntInfo.getId());
                throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
            }
            dbsUtil.dbsEndTransaction(true);
        } catch (Exception e) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error(cc.rengu.utility.base.StringUtil.ExceptionToString(e));
            throw new BizException(RespCodeEnum.SYSTEM_BUSYNESS.getRespCode(), RespCodeEnum.SYSTEM_BUSYNESS.getRespDesc());
        }
    }

}
